package com.atguigu.educenter.controller;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.educenter.utils.ConstantWxUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @author He Wentao
 * @since 2022/9/21 21:01
 */
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
    @Resource
    ConstantWxUtils utils;

    @Resource
    private UcenterMemberService service;

    // 生成微信扫描二维码
    @GetMapping("login")
    public String getWxCode(){
        // 微信开放平台授权baseUrl ‰s相当于? 代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect"+
                "?appid=%s"+
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login"+
                "&state=%s"+
                "#wechat_redirect";

        // 最终拼接 url
        String url = "";

        try {
            url = String.format(baseUrl,
                    utils.getApp_id(),
                    URLEncoder.encode(utils.getRedirect_url(),"utf-8"), // 按照要求，进行编码处理
                    "atguigu");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return "redirect:"+url;

    }

    // 获取扫描人信息，并添加数据
    @GetMapping("callback")
    public String callback(String code,String state){

        // 这个回调方法中，能够得到扫描信息 ！！！！！
        System.out.println(code+"***********"+state);

        // 根据传递过来的 code 值，请求固定的接口地址，得到 accsess_token 和 openid
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"+
                "?appid=%s"+
                "&secret=%s"+
                "&code=%s"+
                "&grant_type=authorization_code";
        // 传入参数
        String accessTokenURL = String.format(baseAccessTokenUrl, utils.getApp_id(), utils.getApp_secret(), code);

        // 使用 spring自带的 restT RestTemplate 进行发送请求
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));

        // 发送请求
        ResponseEntity<String> entity = restTemplate.getForEntity(accessTokenURL, String.class);

        // 响应体数据
        String body = entity.getBody();

        // 获取响应类型，如：json/text
        MediaType contentType = entity.getHeaders().getContentType();

        // 响应状态码枚举类
        HttpStatus statusCode = entity.getStatusCode();

        System.out.println(body+"****"+contentType+"*****"+statusCode+"********");

        // 转换为 map 获取到指定参数
        Gson gson = new Gson();
        HashMap hashMap = gson.fromJson(body, HashMap.class);

        String access_token = (String) hashMap.get("access_token");
        String openid = (String) hashMap.get("openid");


        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",openid);
        UcenterMember one = service.getOne(wrapper);

        if (one == null) {
            // 根据指定参数，获取到用户具体信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo"+
                    "?access_token=%s"+
                    "&openid=%s";

            String userIndoUrl = String.format(baseUserInfoUrl, access_token, openid);
            // 发送请求
            ResponseEntity<String> entity2 = restTemplate.getForEntity(userIndoUrl, String.class);

            // 响应体数据
            String body2 = entity2.getBody();

            System.out.println(body2);

            // 转换为 map 获取到指定参数
            HashMap hashMap2 = gson.fromJson(body2, HashMap.class);

            String nickname = (String) hashMap2.get("nickname"); // 昵称
            String headimgurl = (String) hashMap2.get("headimgurl"); // 头像地址

            one = new UcenterMember(); // 初始化
            one.setAvatar(headimgurl); // 设置值
            one.setNickname(nickname);
            one.setOpenid(openid);

            service.save(one);
        }
        // id 是回显的数据
        String jwtToken = JwtUtils.getJwtToken(one.getId(), one.getNickname());

        // 重定向到前台地址
        return "redirect:http://localhost:3000?token="+jwtToken;
    }


}














